package com.bjpowerndoe.ylb.web.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bjpowerndoe.ylb.common.AppConsts;
import com.bjpowerndoe.ylb.common.RedisKey;
import com.bjpowerndoe.ylb.web.config.SmsConfig;
import com.bjpowerndoe.ylb.web.service.inter.SmsManagerService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.FallbackExceptionTranslationStrategy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@RequiredArgsConstructor
@Service
public class SmsManagerServiceImpl implements SmsManagerService {


    private final SmsConfig smsConfig;
    private final StringRedisTemplate stringRedisTemplate;

    //判断注册验证码是否可用

    // true: 可以继续使用 ； false 需要重新发送
    @Override
    public boolean checkSmsRegister(String phone,String action) {
        String key = "";
        if( AppConsts.SMS_ACTION_REGISTER.equalsIgnoreCase(action)) {
            key = RedisKey.SMS_REGISTER_CODE + phone;
        }
        else if(AppConsts.SMS_ACTION_LOGIN.equalsIgnoreCase(action)){
            key = RedisKey.SMS_LOGIN_CODE + phone;
        }

        Long second = stringRedisTemplate.getExpire(key);

        /**
         *  -1 永久    true
         *  -2 不存在  false
         *  >=0 剩余的秒    0-150
         *  false（<30秒）：false
         */
        if( second != null ){
            if( second == -1){
                return true;
            } else if( second == -2 ){
                return false;
            } else if( second < 30  ){
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    //准备短信的数据，参数
    @Override
    public boolean sendSms(String phone, String action) {
        boolean smsHandlerResult = false;
        String key = "";
        String code = "";
        String smsText = "";
        //准备发送的短信内容：
        if(AppConsts.SMS_ACTION_LOGIN.equalsIgnoreCase(action)){
            //登录
            key = RedisKey.SMS_LOGIN_CODE + phone;
            //注册
            code = RandomUtil.randomNumbers(4);
            //【盈利宝】登录验证码是：%s，3分钟内有效！
            smsText = String.format(smsConfig.getLoginText(), code);

        } else  if( AppConsts.SMS_ACTION_REGISTER.equalsIgnoreCase(action)){
            //注册
            key = RedisKey.SMS_REGISTER_CODE + phone;
            //注册
            code = RandomUtil.randomNumbers(4);
            //【盈利宝】注册验证码是：%s，3分钟内有效！
            smsText = String.format(smsConfig.getRegisterText(), code);
        }
        System.out.printf(action + ",验证码："+code);
        //调用创信的接口
        boolean sendOk = handleSmsApi(phone, smsText);
        //存储验证码到redis
        if( sendOk ) {
            stringRedisTemplate.opsForValue().set(key,code,3, TimeUnit.MINUTES);
            //判断redis存储成功
            if(  stringRedisTemplate.hasKey(key) ) {
                smsHandlerResult = true;
            }
        }
        return smsHandlerResult;
    }


    //调用创信的接口
    private boolean handleSmsApi(String phone,String smsText){

        boolean sendOk = false;
        Map<String,Object> param = new HashMap<>();
        param.put("mobile",phone);
        param.put("content",smsText);
        param.put("appkey",smsConfig.getAppkey());

        try{
            //String result = HttpUtil.get(smsConfig.getUrl(), param, 6000);
            String result = "{\n" +
                    "    \"code\": \"10000\",\n" +
                    "    \"charge\": false,\n" +
                    "    \"remain\": 1305,\n" +
                    "    \"msg\": \"查询成功\",\n" +
                    "    \"result\": {\n" +
                    "        \"ReturnStatus\": \"Success\",\n" +
                    "        \"Message\": \"ok\",\n" +
                    "        \"RemainPoint\": 420842,\n" +
                    "        \"TaskID\": 18424321,\n" +
                    "        \"SuccessCounts\": 1\n" +
                    "    }\n" +
                    "}";
            if(StrUtil.isNotBlank(result)){
                JSONObject obj = JSONUtil.parseObj(result);
                if("10000".equals(obj.getStr("code"))){

                    //System.out.println("obj.getJSONObject(\"result\") = " + obj.getJSONObject("result"));
                    // 获取 result 中的ReturnStatus
                    if( obj.getJSONObject("result") != null ){
                       if("success".equalsIgnoreCase(
                               obj.getJSONObject("result").getStr("ReturnStatus"))){
                           sendOk = true;
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return sendOk;
    }
}
